<template>
  <div class="h-screen w-screen flex flex-col bg-gradient-to-b from-gray-50 to-gray-100 relative">
    <!-- Header -->
    <header class="flex h-16 items-center justify-center bg-blue-600 text-white shadow-md">
      <p class="text-4xl font-semibold">确认订单</p>
    </header>

    <!-- Scrollable Content -->
    <div class="flex-1 overflow-auto p-3 box-border pb-20 space-y-3">
      <!-- Address Card -->
      <div class="bg-gradient-to-r from-blue-400 to-blue-500 p-2 rounded-lg shadow-md text-white">
        <h5 class="text-xl font-light">订单配送至：</h5>
        <div class="flex justify-between items-center my-1 font-bold cursor-pointer" @click="goToAddress">
          <p class="w-90% truncate text-2xl">{{ address }}</p>
          <i class="fa fa-angle-right text-3xl opacity-80"></i>
        </div>
        <p class="text-xl mt-1">{{ recipient }} {{ phone }}</p>
      </div>

      <!-- Shop Name -->
      <h3 class="p-3 text-2xl text-gray-700 border-b border-solid border-gray-300 bg-white rounded-lg shadow-sm font-medium">
        {{ shopName }}
      </h3>

      <!-- Order Items List -->
      <ul v-if="orderItems.length > 0" class="space-y-2 bg-white rounded-lg shadow-md p-3">
        <li v-for="(item, index) in orderItems" :key="index"
            class="flex items-center justify-between py-2 text-gray-800 border-b border-gray-200 last:border-0">
          <div class="flex items-center">
            <img :src="item.image" :alt="item.name" class="w-12 h-12 object-cover rounded-md shadow">
            <p class="ml-3 text-lg font-medium">{{ item.name }} x {{ item.quantity }}</p>
          </div>
          <p class="text-lg font-semibold text-green-600">￥{{ (item.price * item.quantity).toFixed(2) }}</p>
        </li>
      </ul>
      <div v-else class="text-center text-lg text-gray-400 bg-white p-5 rounded-lg shadow-md">
        暂无订单商品
      </div>

      <!-- Delivery Fee -->
      <div v-if="orderItems.length > 0" class="mt-3 p-3 text-gray-700 border-t border-solid border-gray-200 bg-white shadow-md rounded-lg">
        <div class="flex justify-between items-center">
          <p class="text-lg">配送费</p>
          <p class="text-lg font-semibold text-green-600">￥{{ deliveryFee.toFixed(2) }}</p>
        </div>
      </div>
    </div>

    <!-- Footer Payment Bar -->
    <div class="fixed bottom-15 left-0 right-0 h-16 flex border-t border-solid border-gray-200 bg-white z-10 shadow-lg">
      <div class="flex-2 flex items-center justify-center bg-gray-900 text-white text-3xl font-bold rounded-bl-lg">
        ￥{{ totalPrice.toFixed(2) }}
      </div>
      <div
          class="flex-1 flex items-center justify-center bg-green-600 text-white text-3xl font-bold cursor-pointer active:bg-green-700 transition-all duration-200"
          :class="{ 'opacity-50 cursor-not-allowed': orderItems.length === 0 }"
          @click="goToPayment"
      >
        去支付
      </div>
    </div>

    <!-- Footer Menu Component -->
    <FooterMenu />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FooterMenu from "@/components/common/FooterMenu.vue"

const route = useRoute()
const router = useRouter()

// Data reception
const shopName = ref(route.query.shopName || '万家饺子（软件园E18店)');
const deliveryFee = ref(Number(route.query.deliveryFee) || 3);
const itemsQuery = decodeURIComponent(route.query.items || '[]');

const orderItems = ref([])

onMounted(() => {
  try {
    const parsed = JSON.parse(itemsQuery)
    if (Array.isArray(parsed)) {
      orderItems.value = parsed
    } else {
      console.warn('解析出的数据不是数组:', parsed)
    }
  } catch (e) {
    console.error('解析订单数据失败', e)
    orderItems.value = []
  }
})

// Calculate total price
const totalPrice = computed(() => {
  if (orderItems.value.length === 0) return 0;
  const itemsTotal = orderItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  // 示例：满减规则（>= 50 免配送费）
  const isFreeDelivery = itemsTotal >= 50
  return itemsTotal + (isFreeDelivery ? 0 : deliveryFee.value)
})

const goToPayment = () => {
  if (orderItems.value.length === 0) {
    console.log('没有订单商品，无法去支付');
    return;
  }
  router.push({
    path: '/payment',
    query: {
      shopName: shopName.value,
      deliveryFee: deliveryFee.value,
      items: encodeURIComponent(JSON.stringify(orderItems.value))
    }
  })
}

const goToAddress = () => {
  console.log('跳转到地址选择页面');
  // Implement address selection logic
}

// 新增：将地址信息拆分为变量，方便复用和样式控制
const address = ref('云南省昆明市云南大学（呈贡校区）')
const recipient = ref('户先生')
const phone = ref('13656785432')
</script>


